package com.example.ormsqlsplicingframe1.proxy;

import com.example.ormsqlsplicingframe1.utlis.CopyUtils;
import com.example.ormsqlsplicingframe1.utlis.ProxySessionUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;

@Slf4j
public class LazyProxy implements MethodInterceptor {

    //保存字段
    private Set<String> methodGet;

    //原数据
    private Object target;

    //代理对象
    private Object proxy;

    public LazyProxy(Object target) {
        this.target = target;
        this.methodGet =new HashSet<>();
    }

    @Override
    public Object intercept(Object var1, Method var2, Object[] var3, MethodProxy var4) throws Throwable {

        String methodName = var2.getName();

        Object invoke = var2.invoke(target, var3);

        if (invoke == null && !methodName.contains(methodName)){
            if(methodName.startsWith("is")){
                methodName =  methodName.substring(2);
            }else if(methodName.startsWith("get")){
                methodName = methodName.substring(3);
            }else{
                return  invoke;
            }

            if (!ProxySessionUtils.route().isOpenTransaction()){
                log.error("没有开启代理事务");
                return null;
            }

            //String fieldName = StringUtil.toLowerCaseFirstOne(methodName);

            //Field field = ReflectionUtils.findField(var1.getClass(), fieldName);

            methodGet.add(methodName);

            invoke =var2.invoke(target,var3);


        }


        return invoke;
    }

    @SneakyThrows
    public Object getProxyInstance(){

        if (proxy != null){
            return proxy;
        }
        proxy = CopyUtils.UpdateCopy(target, target.getClass().newInstance());
        return proxy;

    }
}
